package com.meixiang.view;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Scroller;

import com.meixiang.R;

import java.util.LinkedList;
import java.util.List;

/**
 * 滑动finish
 */
public class SwipeBackLayout extends FrameLayout {
    private static final String TAG = SwipeBackLayout.class.getSimpleName();
    //当前View
    private View mContentView;
    //移动的最小距离
    private int mTouchSlop;
    //按下的X轴
    private int downX;
    //按下时的Y轴
    private int downY;
    //零时储存的X轴
    private int tempX;
    //
    private int ScrollerX;

    private long downTime;
    //用于滚动的helper类
    private Scroller mScroller;
    //当前view的宽度
    private int viewWidth;
    private boolean isSilding=false;
    private boolean isFinish;
    private Drawable mShadowDrawable;
    private Activity mActivity;
    private List<ViewPager> mViewPagers = new LinkedList<ViewPager>();

    public SwipeBackLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        //getScaledTouchSlop是一个距离，表示滑动的时候，手的移动要大于这个距离才开始移动控件。
        // 如果小于这个距离就不触发移动控件，如viewpager就是用这个距离来判断用户是否翻页
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mScroller = new Scroller(context);

        //为了解决api版本过高的 引用图片出错的原因
        if(Build.VERSION.SDK_INT >=21){
            mShadowDrawable=getResources().getDrawable(R.mipmap.shadow_left,null);
        }else {
            mShadowDrawable = ContextCompat.getDrawable(context,R.mipmap.shadow_left);
        }
    }


    public void attachToActivity(Activity activity) {
        mActivity = activity;
        TypedArray a = activity.getTheme().obtainStyledAttributes(
                new int[] { android.R.attr.windowBackground });
        int background = a.getResourceId(0, 0);
        a.recycle();

        ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
        ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
        decorChild.setBackgroundResource(background);
        decor.removeView(decorChild);
        addView(decorChild);
        setContentView(decorChild);
        decor.addView(this);
    }

    private void setContentView(View decorChild) {
        mContentView = (View) decorChild.getParent();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        downTime=System.currentTimeMillis();
        ViewPager mViewPager = getTouchViewPager(mViewPagers, ev);
        /**
         * 当前页面有Viewpager或者按下的点大于100时，不拦截。
         */
        if(mViewPager != null && mViewPager.getCurrentItem() != 0||ev.getRawX()>ScrollerX){
            isSilding = false;
            return super.onInterceptTouchEvent(ev);
        }

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = tempX = (int) ev.getRawX();
                downY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getRawX();
                if (moveX - downX > mTouchSlop
                        && Math.abs((int) ev.getRawY() - downY) < mTouchSlop) {
                    //当滑动时，进行拦截
                    return true;
                }
        }

        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (event.getRawX()>ScrollerX){
                 return false;
                }

                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) event.getRawX();
                int deltaX = tempX - moveX;
                    if (moveX - downX > mTouchSlop
                            && Math.abs((int) event.getRawY() - downY) < mTouchSlop) {
                        isSilding = true;
                    }
                    if ( moveX - downX >= 0 && isSilding) {
                        if (mContentView.getScrollX()>=0&&tempX>moveX){
                            mContentView.scrollBy(0, 0);
                        }else{
                            mContentView.scrollBy(deltaX, 0);
                        }
                    }
                tempX = moveX;
                break;
            case MotionEvent.ACTION_UP:
                isSilding = false;
                long upTime=System.currentTimeMillis();
                //Log.e("time",upTime-downTime+"");
               if (mContentView.getScrollX() <= -viewWidth / 3) {
                    isFinish = true;
                    scrollRight();
                }else if ( mContentView.getScrollX() <= -ScrollerX&&upTime-downTime<150){
                    isFinish = true;
                    scrollRight();
               }else {
                    scrollOrigin();
                    isFinish = false;
                }
                break;
        }

        return true;
    }

    private void getAlLViewPager(List<ViewPager> mViewPagers, ViewGroup parent){
        int childCount = parent.getChildCount();
        for(int i=0; i<childCount; i++){
            View child = parent.getChildAt(i);
            if(child instanceof ViewPager){
                mViewPagers.add((ViewPager)child);
            }else if(child instanceof ViewGroup){
                getAlLViewPager(mViewPagers, (ViewGroup)child);
            }
        }
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private ViewPager getTouchViewPager(List<ViewPager> mViewPagers, MotionEvent ev){
        if(mViewPagers == null || mViewPagers.size() == 0){
            return null;
        }
        Rect mRect = new Rect();
        for(ViewPager v : mViewPagers){
            v.getHitRect(mRect);
            int[] location=new int[2];
            v.getLocationInWindow(location);
            int x=location[0];
            int y=location[1];
            // mRect.contains((int)ev.getX(), (int)ev.getY())
            if(ev.getY()>=y&&ev.getY()<=y+mRect.height()&&ev.getX()>=x&&ev.getX()<=x+mRect.width()){
                return v;
            }
        }
        return null;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            viewWidth = this.getWidth();
            ScrollerX=viewWidth/8;
            getAlLViewPager(mViewPagers, this);
           // Log.i(TAG, "ViewPager size = " + mViewPagers.size());
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (mShadowDrawable != null && mContentView != null) {

            int left = mContentView.getLeft()
                    - mShadowDrawable.getIntrinsicWidth();
            int right = left + mShadowDrawable.getIntrinsicWidth();
            int top = mContentView.getTop();
            int bottom = mContentView.getBottom();

            mShadowDrawable.setBounds(left, top, right, bottom);
            mShadowDrawable.draw(canvas);
            if (mContentView.getScrollX()<= -viewWidth+mShadowDrawable.getIntrinsicWidth()){
                mShadowDrawable=null;
                mActivity.finish();
            }
        }

    }


    private void scrollRight() {
        final int delta = (viewWidth + mContentView.getScrollX());
        mScroller.startScroll(mContentView.getScrollX(), 0, -delta + 1, 0,
                300);

        postInvalidate();
    }

    private void scrollOrigin() {
        int delta = mContentView.getScrollX();
        mScroller.startScroll(mContentView.getScrollX(), 0, -delta, 0,
                Math.abs(delta));
        postInvalidate();
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            mContentView.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();

            if (mScroller.isFinished() && isFinish) {
                mActivity.finish();
            }
        }
    }

}
